<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          type="primary"
          @click="handleSearchList"
          size="s米糕"
        >
          查询搜索
        </el-button>
        <el-button
          style="float: right; margin-right: 15px"
          @click="handleResetSearch"
          size="s米糕"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          :model="listQuery"
          size="s米糕"
          label-width="140px"
        >
          <el-form-item label="输入搜索：">
            <el-input
              v-model="listQuery.staffName"
              class="input-width"
              placeholder="姓名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="职责：">
            <el-select
              v-model="listQuery.post"
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option label="前道" :value="0"></el-option>
              <el-option label="后道" :value="1"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="状态：">
            <el-select
              v-model="status"
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option label="正常" :value="0"></el-option>
              <el-option label="请假" :value="1"></el-option>
              <el-option label="离职" :value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="请假日期：">
            <el-date-picker
              v-model="searchAskForLeave"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              :default-time="['9:00:00', '18:00:00']"
              clearable
            >
              >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="地区：" v-if="false">
            <el-select
              placeholder="省"
              clearable
              filterable
              @change="searchAreaChange"
              v-model="listQuery.areaId"
            >
              <el-option
                v-for="(item, index) in areas"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-select
              style="margin-left: 10px"
              placeholder="市"
              clearable
              filterable
              v-model="listQuery.cityId"
            >
              <el-option
                v-for="(item, index) in urbanList1"
                :key="index"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="地区：">
            <el-select
              placeholder="地区"
              clearable
              filterable
              v-model="cityValue"
              value-key="label"
            >
              <el-option
                v-for="(item, index) in cityOptions"
                :key="index"
                :label="item.cityName"
                :value="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表, 正常状态的员工：{{normal}}人， 新人：{{ newStaff }}</span>
      <el-button
        size="mini"
        type="primary"
        class="btn-add"
        @click="handleAdd()"
        style="margin-left: 20px"
        >添加</el-button
      >
    </el-card>
    <div class="table-container">
      <el-table
        ref="adminTable"
        :data="list"
        style="width: 100%"
        v-loading="listLoading"
        border
      >
        <el-table-column label="姓名" align="center">
          <template slot-scope="scope">{{ scope.row.staffName }}</template>
        </el-table-column>
        <el-table-column label="别名" align="center">
          <template slot-scope="scope">
            <el-tag type="success" hit>{{ scope.row.salesId }}</el-tag></template>
        </el-table-column>
        <el-table-column label="地区" align="center">
          <template slot-scope="scope">{{
            scope.row.cityName || scope.row.areaName || ""
          }}</template>
        </el-table-column>
        <el-table-column label="新人" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleStatusChange(scope.$index, scope.row)"
              :active-value="1"
              :inactive-value="0"
              v-model="scope.row.newPeople"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="职责" align="center">
          <template slot-scope="scope">
            {{ postOptions[scope.row.post] || "无" }}
          </template>
        </el-table-column>

        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <!-- {{ workStatuss(scope.row.leaveStart, scope.row.leaveEnd) }} -->
            {{
              scope.row.depart === 0
                ? statusOptionss[2]
                : statusOptionss[scope.row.status]
            }}
            <el-tooltip
              effect="dark"
              placement="top-start"
              v-if="tooltipShow(scope.row)"
            >
              <div slot="content">
                {{ formatDateTime(scope.row.leaveStart * 1000) }} ~
                {{ formatDateTime(scope.row.leaveEnd * 1000) }}
              </div>
              <el-icon
                class="el-icon-time"
                style="color: #409eff; font-size: 16px"
              ></el-icon>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="离职" width="140" align="center">
          <template slot-scope="scope">
            <el-switch
              @change="handleStatusChange(scope.$index, scope.row)"
              :active-value="0"
              :inactive-value="1"
              v-model="scope.row.depart"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="家庭住址" align="center">
          <template slot-scope="scope">
            {{ scope.row.homeAddress || "无" }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.$index, scope.row)"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div
      class="pagination-container"
      style="
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding-bottom: 20px;
      "
    >
      <el-pagination
        background
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="pageSize"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
  <script>

import {
  staffList,
  totalByNewStaffBySearch,
  totalByNewStaff,
  staffListSearch,
  updateStaff,
  addStaff,
  getArea,
  getUrban,
} from "@/api/staff";
import { fetchAllRoleList } from "@/api/role";
import { formatDate } from "@/utils/date";
import { maxNum, minNum } from "@/utils/max";

import { convertEmptyToNull } from "@/utils/null";
import { filterCitySelect } from "@/utils/filterCity";
const defaultListQuery = {
  pageNum: 1,
  staffName: null,
  post: null,
  leaveStart: null,
  leaveEnd: null,
  status: null,
  depart: null,
  lastId: 0,
  areaId: null,
  cityId: null,
};


const statusOptions = [
  {
    label: "正常",
    value: 0,
  },
  {
    label: "请假",
    value: 1,
  },
];

const selectStatus = [
  {
    status: 0,
    depart: 1,
  },
  {
    status: 1,
    depart: null,
  },
  {
    status: null,
    depart: 0,
  },
  {
    status: null,
    depart: null,
  },
];

const statusOptionss = ["正常", "请假", "离职"];

const postOptions = ["前道", "后道"];

const datePicker = {
  shortcuts: [
    {
      text: "半天",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        end.setTime(end.getTime() + 3600 * 1000 * 9);
        picker.$emit("pick", [start, end]);
      },
    },
    {
      text: "最近一周",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit("pick", [start, end]);
      },
    },
    {
      text: "最近一个月",
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        picker.$emit("pick", [start, end]);
      },
    },
  ],
};
export default {
  name: "staffList",
  data() {
    return {
      statusOptionss,
      listQuery: Object.assign({}, defaultListQuery),
      list: [],
      total: 0,
      pageSize: null,
      listLoading: false,
      dialogVisible: false,
      allocDialogVisible: false,
      allocRoleIds: [],
      allRoleList: [],
      normal:0,
      allocAdminId: null,
      value: "",
      statusOptions,
      datePicker,
      newStaff: 0,
      postOptions,
      askForLeave: null,
      searchAskForLeave: null,
      status: "",
      allDagongren: [],
      allParams: {
        pageNum: 1,
        lastId: 0,
        pageSize: null,
        total: 0,
      },
      cityOptions: [],
      cityValue: null,
    };
  },
  created() {
    this.getList();
    // this.getAreas();
    this.getAllDaGongren();
  },
  mounted() {
    totalByNewStaff(this);
  },
  methods: {
   
    async searchAreaChange(val) {
      if (val) {
        const data = await this.getUrbans({ id: val });
        this.urbanList1 = data;
        this.listQuery.cityId = data[0].id;
      } else {
        this.urbanList1 = [];
        this.listQuery.cityId = null;
      }
    },

    //排序 倒序
    sortList() {
      this.list.length &&
        this.list.sort(function (a, b) {
          return b.id - a.id;
        });
    },

    // 弹窗关闭回调
    closed() {
      this.$refs.adminForm.clearValidate();
    },
   
    handleResetSearch() {
      this.status = "";
      this.cityValue = null;
      this.listQuery = Object.assign({}, defaultListQuery);
      this.searchAskForLeave = null;
      this.handleSearchList();
    },
    handleSearchList() {
      this.listQuery.pageNum = 1;
      this.listQuery.lastId = 0;
      this.listQuery.leaveStart = this.searchAskForLeave
        ? new Date(this.searchAskForLeave[0]).getTime()
        : null;
      this.listQuery.leaveEnd = this.searchAskForLeave
        ? new Date(this.searchAskForLeave[1]).getTime()
        : null;
      if (this.cityValue || this.cityValue === 0 || this.cityValue === 1) {
        this.listQuery.areaId = this.cityOptions[this.cityValue].areaId;
        this.listQuery.cityId = this.cityOptions[this.cityValue].cityId;
      } else {
        this.listQuery.areaId = null;
        this.listQuery.cityId = null;
      }
      if (this.status || this.status === 0 || this.status === 1) {
        this.listQuery = Object.assign(
          this.listQuery,
          selectStatus[this.status]
        );
      } else {
        this.listQuery = Object.assign(this.listQuery, selectStatus[3]);
      }
      convertEmptyToNull(this.listQuery);
      this.getList();

      totalByNewStaffBySearch(this.listQuery, this);
    },

    async handleUpdate(index, row) {
     
      sessionStorage.setItem("staffItem", JSON.stringify(row));
      console.log("row.id", row.id);
      this.$router.push({
        path:`/staff/edit/${row.id}`,
      })

    
    },
   
    handleAllocDialogConfirm() {
      this.$confirm("是否要确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let params = new URLSearchParams();
        params.append("adminId", this.allocAdminId);
        params.append("roleIds", this.allocRoleIds);
        allocRole(params).then((response) => {
          this.$message({
            message: "分配成功！",
            type: "success",
          });
          this.allocDialogVisible = false;
        });
      });
    },
    handleSelectRole(index, row) {
      this.allocAdminId = row.id;
      this.allocDialogVisible = true;
      this.getRoleListByAdmin(row.id);
    },
    // 获取所有的员工
    getAllDaGongren() {
      if (this.allParams.pageNum === 1) {
        this.allParams.lastId = 0;
      } else {
        this.allParams.lastId = maxNum(this.allDagongren, "id");
      }
      staffListSearch({
        pageNum: this.allParams.pageNum,
        lastId: this.allParams.lastId,
      }).then((res) => {
        this.allDagongren = this.allDagongren.concat(res.data.data);
        this.allParams.total = res.data.total;
        this.allParams.pageSize = res.data.pageSize;
        let totalPage = Math.ceil(res.data.total / res.data.pageSize);
        if (this.allParams.pageNum < totalPage) {
          this.allParams.pageNum++;
          this.getAllDaGongren();
        } else {
          this.cityOptions = filterCitySelect(this.allDagongren);
        }
      });
    },

    // 更新地区搜索列表
    updateCityOptions() {
      this.allParams.pageNum = 1;
      this.allParams.lastId = 0;
      this.getAllDaGongren();
    },

    getList() {
      this.listLoading = true;
      staffListSearch(this.listQuery).then((response) => {
        this.listLoading = false;
        this.list = response.data.data;
        this.total = response.data.total;
        this.pageSize = response.data.pageSize;
        this.sortList();
        this.$forceUpdate();
      });
    },
    getAllRoleList() {
      fetchAllRoleList().then((response) => {
        this.allRoleList = response.data;
      });
    },
    getRoleListByAdmin(adminId) {
      getRoleByAdmin(adminId).then((response) => {
        let allocRoleList = response.data;
        this.allocRoleIds = [];
        if (allocRoleList != null && allocRoleList.length > 0) {
          for (let i = 0; i < allocRoleList.length; i++) {
            this.allocRoleIds.push(allocRoleList[i].id);
          }
        }
      });
    },

    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      if (val === 1) {
        this.listQuery.lastId = 0;
        this.getList();
      }
    },
    handleAdd() {
      this.$router.push({
        path: "/staff/add",
      });
    },
    handleStatusChange(index, row) {
      this.$confirm("是否要修改该状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateStaff(row).then((response) => {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消修改",
          });
          this.getList();
        });
    },
    handleDelete(index, row) {
      this.$confirm("是否要删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteAdmin(row.id).then((response) => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        });
      });
    },
  },

  watch: {
    askForLeave(newVal) {
      if (newVal) {
        this.admin.leaveStart = newVal[0];
        this.admin.leaveEnd = newVal[1];
      }
    },
    "listQuery.pageNum": {
      handler(newVal, oldVal) {
        if (newVal === 1) {
          this.listQuery.lastId = 0;
          return false;
        } else {
          if (newVal > oldVal && newVal === oldVal + 1) {
            this.listQuery.lastId = maxNum(this.list, "id");
          } else if (newVal > oldVal && newVal !== oldVal + 1) {
            let num = 0;
            num =
              maxNum(this.list, "id") +
              (newVal - oldVal - 1) * (this.pageSize || 30);
            this.listQuery.lastId = num;
          } else if (newVal < oldVal) {
            let num1 = 0;
            num1 =
              minNum(this.list, "id") -
              1 -
              (oldVal - newVal) * (this.pageSize || 30);
            this.listQuery.lastId = num1;
          }
        }
        this.getList();
      },
      deep: true,
    },
  },
  computed: {
    tooltipShow() {
      return (row) => {
        let start = new Date(row.leaveStart * 1000).getTime();
        let end = new Date(row.leaveEnd * 1000).getTime();
        let now = new Date().getTime();
        if (now < end) {
          return true;
        } else {
          return false;
        }
      };
    },
    formatDateTime() {
      return (time) => {
        if (time == null || time === "") {
          return "N/A";
        }
        let date = new Date(time);
        return formatDate(date, "yyyy/MM/dd hh:mm:ss");
      };
    },
   
    workStatuss() {
      return (s, e) => {
        const time = new Date().getTime() / 1000;
        if (s > 0 && e > 0) {
          if (time >= s && time <= e) {
            return "请假";
          } else {
            return "正常";
          }
        }
        return "正常";
      };
    },
  },
};
</script>
<style scoped>
.my-dialog :deep(.el-dialog) {
  min-width: 700px;
  max-width: 100%;
}
</style>
  
  
  